﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Globalization;
using System.Text;

namespace VSM
{
    public partial class CreateSQ : System.Web.UI.Page
    {
        #region Fields
        //private static DataTable dtHeader;
        //private static DataTable dtContents;
        //private static DataTable dtFreight;
        //private static DataTable dtWhs;
        //private static DataTable dtVatGroup;
        //private static GeneralFunctions GF = null;

        private string TblHeaderName = "OQUT";
        private string TblLineName = "QUT1";
        private string TblLineName1 = "QUT3";
        private string CurrentPageUrl = "/Business/Sales/CreateSQ.aspx";
        private string HeaderKeyName = "DocEntry";
        private String TargetPageUrl = "/Business/Sales/CreateSO.aspx";
        #endregion

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Session[Utils.AppConstants.ID_User] == null
                || Session[Utils.AppConstants.Password] == null
                || Session[Utils.AppConstants.ID_Dealer] == null)
            {
                Response.Redirect("../../Login.aspx");
            }
            if (!IsPostBack)
            {
                ClearScreen();

                string dbType = (string)Session[Utils.AppConstants.ID_Dealer] == "VSM" ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER;
                GeneralFunctions GF = new GeneralFunctions(dbType, Session[Utils.AppConstants.ID_Dealer].ToString());
                Session["SQGF"] = GF;
                // Get Warehouse
                Session["SQdtWhs"] = GF.GetWarehouseByDealerDepartment(dbType, Session[Utils.AppConstants.ID_Dealer].ToString(), Utils.AppConstants.SALES);
                // Get Vat Group
                Session["SQdtVatGroup"] = GF.GetVatGroupByCategory(dbType, "O");
                // Get Model
                Session["SQdtModel"] = GF.GetModelList(dbType);
                // Get Color
                Session["SQdtColor"] = GF.GetColorList(dbType);

                String sqId = Request.QueryString["sq_id"];
                if (!String.IsNullOrEmpty(sqId))
                {
                    LoadData(sqId, ConvertDocType.Get2String(DocType.SALES_QUOTATION));
                    if (lblStatus.Text == "Closed")
                        SetScreenStatus("Close");
                    else if (lblStatus.Text == "OPen")
                        SetScreenStatus("Update");
                }
                else
                {
                    LoadDefault();
                    SetScreenStatus("New");
                }
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void grvSearchResult_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            this.grvSQ.PageIndex = e.NewPageIndex;
            DataTable tblISQ = (DataTable)Session["SQTable"];
            BindData(tblISQ);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void lnkDelete_Click(object sender, EventArgs e)
        {
            try
            {
                GridViewRow row = (GridViewRow)((DataControlFieldCell)((LinkButton)sender).Parent).Parent;
                Label lblNo = (Label)row.FindControl("lblNo");
                DataTable tb = (DataTable)Session["SQTable"];

                if (tb != null)
                {
                    DataRow[] rupdate = tb.Select("No=" + lblNo.Text);
                    if (rupdate.Length > 0)
                    {
                        Dictionary<string, string> dicItem = (Dictionary<string, string>)Session["ChosenItem"];
                        if (dicItem != null)
                        {
                            if (dicItem.ContainsKey(rupdate[0]["ItemCode"].ToString())) dicItem.Remove(rupdate[0]["ItemCode"].ToString());
                        }
                        tb.Rows.Remove(rupdate[0]);
                        int liNo = 1;
                        foreach (DataRow dr in tb.Rows)
                        {
                            dr["No"] = liNo;
                            liNo++;
                        }
                    }
                    this.grvSQ.EditIndex = -1;
                    BindData((DataTable)Session["SQTable"]);
                    updateTableTotalPrice();
                }
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void grvSearchResult_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                e.Row.Attributes.Add("onmouseover", "MouseEvents(this, event)");
                e.Row.Attributes.Add("onmouseout", "MouseEvents(this, event)");
                e.Row.Attributes["style"] = "cursor:pointer";

                string dbType = Session[Utils.AppConstants.ID_Dealer].ToString() == "VSM" ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER;
                GeneralFunctions GF = (GeneralFunctions)Session["SQGF"];
                // Load Model
                DropDownList ddlModel = (DropDownList)e.Row.FindControl("ddlModel");
                Label txtModel = (Label)e.Row.FindControl("txtModel");
                if (ddlModel != null)
                {
                    ddlModel.DataSource = (DataTable)Session["SQdtModel"];
                    ddlModel.DataValueField = "Code";
                    ddlModel.DataTextField = "Name";
                    ddlModel.DataBind();
                    ddlModel.Items.Insert(0, "");
                    
                    if (txtModel != null) ddlModel.SelectedValue = txtModel.Text;
                }
                // Load Product
                DropDownList ddlProduct = (DropDownList)e.Row.FindControl("ddlProduct");
                if (ddlProduct != null)
                {
                    ddlProduct.DataSource = GF.GetProductByModel(dbType, txtModel.Text);
                    ddlProduct.DataValueField = "Code";
                    ddlProduct.DataTextField = "Name";
                    ddlProduct.DataBind();
                    ddlProduct.Items.Insert(0, "");
                    Label txtProduct = (Label)e.Row.FindControl("txtProduct");
                    if (txtProduct != null) ddlProduct.SelectedValue = txtProduct.Text;
                }
                // Load Color
                DropDownList ddlColor = (DropDownList)e.Row.FindControl("ddlColor");
                if (ddlColor != null)
                {
                    ddlColor.DataSource = (DataTable)Session["SQdtColor"];
                    ddlColor.DataValueField = "Code";
                    ddlColor.DataTextField = "Name";
                    ddlColor.DataBind();
                    ddlColor.Items.Insert(0, "");
                    Label txtColorCode = (Label)e.Row.FindControl("txtCorlorCode");
                    if (txtColorCode != null) ddlColor.SelectedValue = txtColorCode.Text;
                }

                // Load Whs
                DropDownList ddlWhs = (DropDownList)e.Row.FindControl("ddlWhs");
                if (ddlWhs != null)
                {
                    ddlWhs.DataSource = (DataTable)Session["SQdtWhs"];
                    ddlWhs.DataValueField = "WhsCode";
                    ddlWhs.DataTextField = "WhsName";
                    ddlWhs.DataBind();
                    HiddenField hdnWhsCode = (HiddenField)e.Row.FindControl("hdnWhsCode");
                    if (hdnWhsCode != null) ddlWhs.SelectedValue = hdnWhsCode.Value;
                }

                // Load Vat Group
                DropDownList ddlVatGrp = (DropDownList)e.Row.FindControl("ddlVatGroup");
                if (ddlVatGrp != null)
                {
                    DataTable dtVatGroup = (DataTable)Session["SQdtVatGroup"];
                    ddlVatGrp.DataSource = dtVatGroup;
                    ddlVatGrp.DataValueField = "Code";
                    ddlVatGrp.DataTextField = "Name";
                    ddlVatGrp.DataBind();
                    HiddenField hdnVatGroup = (HiddenField)e.Row.FindControl("hdnVatGroup");
                    if (hdnVatGroup != null)
                    {
                        ddlVatGrp.SelectedValue = hdnVatGroup.Value;
                        DataRow[] rRate = dtVatGroup.Select("Code='" + hdnVatGroup.Value + "'");
                        if (rRate.Length > 0)
                        {
                            HiddenField hdnVatPrcnt = (HiddenField)e.Row.FindControl("hdnVatPrcnt");
                            hdnVatPrcnt.Value = rRate[0]["Rate"].ToString();
                        }
                    }
                }
            }
        }

  
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void txtOrderQuantity_OnTextChanged(object sender, EventArgs e)
        {
            try
            {
                this.lblError.Visible = false;
                GridViewRow row = (GridViewRow)((DataControlFieldCell)((TextBox)sender).Parent).Parent;
                ViewState["rowindex"] = row.RowIndex;
                TextBox txtQuantity = (TextBox)row.FindControl("txtOrderQuantity");
                if (txtQuantity.Text.Trim().Length == 0)
                {
                    ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "CallJS", "alert('Pls input quantity');", true);
                    txtQuantity.Focus();
                    return;
                }

                Label lblNo = (Label)row.FindControl("lblNo");
                DataTable tb = (DataTable)Session["SQTable"];

                if (tb != null)
                {
                    DataRow[] rupdate = tb.Select("No=" + lblNo.Text );
                    if (rupdate.Length > 0)
                    {
                        rupdate[0]["Quantity"] = txtQuantity.Text;
                        updateRowTotalPrice(rupdate[0], "Quantity");
                    }
                }

                this.grvSQ.EditIndex = -1;

                BindData(tb);
                //CalcTotal(tb);
                updateTableTotalPrice();
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void DeleteItem(object sender, GridViewDeleteEventArgs e)
        {
            try
            {

                e.Cancel = true;
                GridViewRow row = (GridViewRow)this.grvSQ.Rows[e.RowIndex];
                Label lblNo = (Label)row.FindControl("lblNo");
                DataTable tb = (DataTable)Session["SQTable"];

                if (tb != null)
                {
                    DataRow[] rupdate = tb.Select("No=" + lblNo.Text);

                    if (rupdate.Length > 0)
                    {
                        Dictionary<string, string> dicItem = (Dictionary<string, string>)Session["ChosenItem"];
                        if (dicItem != null)
                        {
                            if (dicItem.ContainsKey(rupdate[0]["ItemCode"].ToString()))
                            {
                                dicItem.Remove(rupdate[0]["ItemCode"].ToString());
                            }
                        }
                        tb.Rows.Remove(rupdate[0]);
                    }
                    this.grvSQ.EditIndex = -1;
                    BindData((DataTable)Session["SQTable"]);
                    updateTableTotalPrice();
                }
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
        }

        private double CalculateVatSum(DataRow dr)
        {
            GeneralFunctions GF = (GeneralFunctions)Session["SQGF"];
            double TotalAfDisc = 0, vatPrcnt = 0;
            TotalAfDisc = GF.Object2Double(GF.ResetFormatNumeric(dr["TotalAfDisc"].ToString()), "SumDec");
            vatPrcnt = GF.Object2Double(GF.ResetFormatNumeric(dr["VatPrcnt"].ToString()), "SumDec");
            return (TotalAfDisc * vatPrcnt)/ 100;
        }

        private double CalculateTotalAfDisc(DataRow dr)
        {
            GeneralFunctions GF = (GeneralFunctions)Session["SQGF"];

            double LineTotal = 0, discAmnt = 0, incentiveDiscAmnt = 0;
            LineTotal = GF.Object2Double(GF.ResetFormatNumeric(dr["LineTotal"].ToString()), "SumDec");
            discAmnt = GF.Object2Double(GF.ResetFormatNumeric(dr["U_Discount"].ToString()), "SumDec");
            incentiveDiscAmnt = GF.Object2Double(GF.ResetFormatNumeric(dr["U_IncentiveDiscount"].ToString()), "SumDec");
            return LineTotal - (discAmnt + incentiveDiscAmnt);
        }

        private double CalculateTotal(DataRow dr)
        {
            GeneralFunctions GF = (GeneralFunctions)Session["SQGF"];

            double TotalAfDisc = 0, vatSumAmnt = 0;
            TotalAfDisc = GF.Object2Double(GF.ResetFormatNumeric(dr["TotalAfDisc"].ToString()), "SumDec");
            vatSumAmnt = GF.Object2Double(GF.ResetFormatNumeric(dr["VatSum"].ToString()), "SumDec");
            return TotalAfDisc + vatSumAmnt;
        }

        public void updateRowTotalPrice(DataRow row, string Flag)
        {
            try
            {
                GeneralFunctions GF = (GeneralFunctions)Session["SQGF"];

                double quantity = 0, unitPrice = 0.0, discount = 0, priceAfterDiscount = 0.0, totalBefDisc = 0;
                double VatPrcnt = 0, VatSum = 0, U_Discount = 0, U_IncentiveDiscount = 0, TotalAfDisc = 0, Total = 0;

                quantity = GF.Object2Double(GF.ResetFormatNumeric(row["Quantity"].ToString()), "QtyDec");
                unitPrice = GF.Object2Double(GF.ResetFormatNumeric(row["PriceBefDi"].ToString()), "PriceDec");
                //discount = GF.Object2Double(GF.ResetFormatNumeric(row["DiscPrcnt"].ToString()), "PercentDec");

                // VatPrcnt, U_Discount, U_IncentiveDiscount
                VatPrcnt = GF.Object2Double(GF.ResetFormatNumeric(row["VatPrcnt"].ToString()), "PercentDec");
                U_Discount = GF.Object2Double(GF.ResetFormatNumeric(row["U_Discount"].ToString()), "SumDec");
                U_IncentiveDiscount = GF.Object2Double(GF.ResetFormatNumeric(row["U_IncentiveDiscount"].ToString()), "SumDec");
                
                priceAfterDiscount = GF.Object2Double((Object)(unitPrice * (100 - discount) / 100), "PriceDec");
                totalBefDisc = GF.Object2Double((Object)(priceAfterDiscount * quantity), "SumDec");

                // Total after discount
                TotalAfDisc = totalBefDisc - (U_Discount + U_IncentiveDiscount);
                // VatSum
                VatSum = (TotalAfDisc * VatPrcnt) / 100; 
                // Total
                Total = (TotalAfDisc + VatSum);

                if (string.IsNullOrEmpty(Flag))
                    row["PriceBefDi"] = GF.FormatNumeric(unitPrice.ToString(), "PriceDec");

                //if (string.IsNullOrEmpty(Flag) || Flag.Equals("PriceBefDi") || Flag.Equals("DiscPrcnt"))
                //    row["DiscPrcnt"] = GF.FormatNumeric(discount.ToString(), "PercentDec");

                row["Price"] = GF.FormatNumeric(priceAfterDiscount.ToString(), "PriceDec");
                row["LineTotal"] = GF.FormatNumeric(totalBefDisc.ToString(), "SumDec");
                if (string.IsNullOrEmpty(Flag) || Flag.Equals("PriceBefDi") || Flag.Equals("Quantity"))
                    row["Quantity"] = GF.FormatNumeric(quantity.ToString(), "QtyDec");

                row["TotalAfDisc"] = GF.FormatNumeric(TotalAfDisc.ToString(), "SumDec");
                row["VatSum"] = GF.FormatNumeric(VatSum.ToString(), "SumDec");
                row["Total"] = GF.FormatNumeric(Total.ToString(), "SumDec");

            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
            }
            this.lblError.Visible = true;
        }

        protected void updateDiscPrcnt(DataRow dr)
        {
            GeneralFunctions GF = (GeneralFunctions)Session["SQGF"];
            double orderTotalBeforeDiscount = 0.0, U_DiscountTotal = 0.0, U_IncentiveDiscountTotal = 0.0;
            DataTable tbSQ = (DataTable)Session["SQTable"];

            foreach (DataRow row in tbSQ.Rows)
            {
                if (!"".Equals(row["ItemCode"]))
                {
                    // Subtotal
                    double total = GF.Object2Double((object)GF.ResetFormatNumeric(row["LineTotal"].ToString()), "SumDec");
                    orderTotalBeforeDiscount += total;
                    // Amount Disc.
                    double discAmnt = GF.Object2Double((object)GF.ResetFormatNumeric(row["U_Discount"].ToString()), "SumDec");
                    double IncentiveDisc = GF.Object2Double((object)GF.ResetFormatNumeric(row["U_IncentiveDiscount"].ToString()), "SumDec");
                    U_DiscountTotal += discAmnt;
                    U_IncentiveDiscountTotal += IncentiveDisc;
                }
            }
            dr["DiscSum"] = U_DiscountTotal + U_IncentiveDiscountTotal;
            dr["DiscPrcnt"] = ((U_DiscountTotal + U_IncentiveDiscountTotal) * 100) / orderTotalBeforeDiscount;
        }

        protected void updateTableTotalPrice()
        {
            GeneralFunctions GF = (GeneralFunctions)Session["SQGF"];
            double orderTotalBeforeDiscount = 0.0, orderTotal = 0.0, taxTotal = 0.0, freightCharge = 0.0;
            DataTable tbSQ = (DataTable)Session["SQTable"];

            foreach (DataRow row in tbSQ.Rows)
            {
                if (!"".Equals(row["ItemCode"]))
                {
                    // Subtotal
                    double total = GF.Object2Double((object)GF.ResetFormatNumeric(row["TotalAfDisc"].ToString()), "SumDec");
                    orderTotalBeforeDiscount += total;
                    // VatSum
                    double tax = GF.Object2Double((object)GF.ResetFormatNumeric(row["VatSum"].ToString()), "SumDec");
                    taxTotal += tax;

                    /*
                    double total = GF.Object2Double((object)GF.ResetFormatNumeric(row["LineTotal"].ToString()), "SumDec");
                    double taxRate = GF.Object2Double(row["VatPrcnt"], "RateDec");

                    if (taxRate == 0) taxRate = 10;
                    double tax = total * taxRate / 100;
                    orderTotalBeforeDiscount += total;
                    taxTotal += tax;*/
                }
            }

            this.lblSubTotal.Text = GF.FormatNumeric(orderTotalBeforeDiscount.ToString(), "SumDec");
            this.lblTaxAmount.Text = GF.FormatNumeric(taxTotal.ToString(), "SumDec");

            freightCharge = double.Parse(GF.ResetFormatNumeric(string.IsNullOrEmpty(lblOtherFees.Text) ? "0" : lblOtherFees.Text));
            orderTotal = orderTotalBeforeDiscount + taxTotal + freightCharge;

            this.lblPaymentTotal.Text = GF.FormatNumeric(orderTotal.ToString(), "SumDec");
        }

        private DataTable BuildContents(DataTable dtContent)
        {
            DataTable dt = new DataTable(TblLineName);
            dt.Columns.Add("No");
            dt.Columns.Add("ItemCode");
            dt.Columns.Add("Dscription");
            dt.Columns.Add("U_Model");
            dt.Columns.Add("U_Product");
            dt.Columns.Add("U_Color");
            dt.Columns.Add("PriceBefDi");
            //dt.Columns.Add("DiscPrcnt");
            dt.Columns.Add("Price");
            dt.Columns.Add("UomCode");
            dt.Columns.Add("Quantity");
            dt.Columns.Add("ShipDate");
            dt.Columns.Add("LineTotal");
            dt.Columns.Add("OnHand");
            dt.Columns.Add("OnHand_VSM");
            dt.Columns.Add("Available");

            dt.Columns.Add("VatGroup");
            dt.Columns.Add("VatPrcnt");
            dt.Columns.Add("VatSum");
            // UDF
            dt.Columns.Add("U_Discount");
            dt.Columns.Add("U_IncentiveDiscount");

            dt.Columns.Add("TotalAfDisc");
            dt.Columns.Add("Total");

            dt.Columns.Add("WhsCode");
            dt.Columns.Add("DocEntry");
            dt.Columns.Add("LineNum");
            dt.Columns.Add("BaseType");
            dt.Columns.Add("BaseEntry");
            dt.Columns.Add("BaseLine");

            if (dtContent != null)
            {
                foreach (DataRow dr in dtContent.Rows)
                {
                    DataRow row = dt.NewRow();
                    row["No"] = dr["No"];
                    row["ItemCode"] = dr["ItemCode"];
                    row["Dscription"] = dr["Dscription"];
                    row["U_Model"] = dr["U_Model"];
                    row["U_Product"] = dr["U_Product"];
                    row["U_Color"] = dr["U_Color"];
                    row["PriceBefDi"] = dr["PriceBefDi"];
                    //row["DiscPrcnt"] = dr["DiscPrcnt"];
                    row["WhsCode"] = dr["WhsCode"];
                    row["Price"] = dr["Price"];
                    row["UomCode"] = dr["UomCode"];
                    row["Quantity"] = dr["Quantity"];
                    row["ShipDate"] = dr["ShipDate"];
                    if(dtContent.Columns.Contains("OnHand"))
                    {
                        row["OnHand"] = GetDealerOnHandQty(dr["ItemCode"].ToString(),dr["WhsCode"].ToString());
                        row["OnHand_VSM"] = GetVSMOnHandQty(dr["ItemCode"].ToString());
                        row["Available"] = GetAvailableQty(dr["ItemCode"].ToString());
                    }
                    row["LineTotal"] = dr["LineTotal"];

                    row["VatGroup"] = dr["VatGroup"];
                    row["VatPrcnt"] = dr["VatPrcnt"];
                    row["VatSum"] = dr["VatSum"];
                    // UDF
                    row["U_Discount"] = dr["U_Discount"];
                    row["U_IncentiveDiscount"] = dr["U_IncentiveDiscount"];

                    // Total
                    row["TotalAfDisc"] = CalculateTotalAfDisc(row);
                    row["Total"] = CalculateTotal(row);

                    row["WhsCode"] = dr["WhsCode"];
                    row["DocEntry"] = dr["DocEntry"];
                    row["LineNum"] = dr["LineNum"];
                    row["BaseType"] = dr["BaseType"];
                    row["BaseEntry"] = dr["BaseEntry"];
                    row["BaseLine"] = dr["BaseLine"];
                    dt.Rows.Add(row);
                }
            }
            return dt;
        }

        private string GetAvailableQty(string ItemCode)
        {
            return "*";
            /*
            string lsSqlCommand = "select case when (SUM( IsNull(OnOrder, 0) ) + SUM( IsNull(OnHand, 0) ) - SUM( IsNull(IsCommited, 0) )) > 15 then 15 else (SUM( IsNull(OnOrder, 0) ) + SUM( IsNull(OnHand, 0) ) - SUM( IsNull(IsCommited, 0) )) end As Available";
            lsSqlCommand += " From OITW where ItemCode = '" + ItemCode + "' and WhsCode In ('HCM-SAL', 'HN-SAL') ";
            return GF.GetSingleValue(Utils.AppConstants.VSM, lsSqlCommand, "Available");
             * */
        }

        private string GetVSMOnHandQty(string ItemCode)
        {
            GeneralFunctions GF = new GeneralFunctions(Utils.AppConstants.VSM, Utils.AppConstants.VSM);
            string lsSqlCommand = "select case when (SUM( IsNull(OnOrder, 0) ) + SUM( IsNull(OnHand, 0) ) - SUM( IsNull(IsCommited, 0) )) > 15 then 15 else (SUM( IsNull(OnOrder, 0) ) + SUM( IsNull(OnHand, 0) ) - SUM( IsNull(IsCommited, 0) )) end As Available";
            lsSqlCommand += " From OITW where ItemCode = '" + ItemCode + "' and WhsCode In ('HCM-SAL', 'HN-SAL') ";
            return GF.GetSingleValue(Utils.AppConstants.VSM, lsSqlCommand, "Available");

            /*
            // Get InStock Qty
            string lsSqlCommand = "select SUM(IsNull(OnHand, 0) ) As OnHand";
            lsSqlCommand += " From OITW where ItemCode = '" + ItemCode + "' and WhsCode In ('HCM-SAL', 'HN-SAL') ";
            string lsInStockQty = GF.GetSingleValue(Utils.AppConstants.VSM, lsSqlCommand, "OnHand");

            // Get SO Qty
            lsSqlCommand = "SELECT isNull(SUM(IsCommited), 0) AS SOQty FROM ( ";
            lsSqlCommand += " select isNull(OpenQty, 0) as IsCommited from RDR1 where WhsCode IN ('HCM-SAL', 'HN-SAL') AND LineStatus = 'O' and ItemCode = '" + ItemCode + "' ";
            lsSqlCommand += "UNION ";
            lsSqlCommand += "select isNull(OpenQty, 0) as IsCommited from WTQ1 where FromWhsCod IN ('HCM-SAL', 'HN-SAL') AND LineStatus = 'O' and ItemCode = '" + ItemCode + "' ";
            lsSqlCommand += ") AS A ";
            string lsSOQty = GF.GetSingleValue(Utils.AppConstants.VSM, lsSqlCommand, "SOQty");

            int liQty = int.Parse(string.IsNullOrEmpty(lsInStockQty) ? "0" : lsInStockQty) - int.Parse(string.IsNullOrEmpty(lsSOQty) ? "0" : lsSOQty);

            return liQty > 15 ? "15" : liQty.ToString();*/
        }

        private string GetDealerOnHandQty(string ItemCode, string WhsCode)
        {
            string dbType = Session[Utils.AppConstants.ID_Dealer].ToString().Equals(Utils.AppConstants.VSM) ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER;
            GeneralFunctions GF = new GeneralFunctions(dbType, Session[Utils.AppConstants.ID_Dealer].ToString());

            string lsSqlCommand = "select isNull(OnHand, 0) As OnHand From OITW where ItemCode = '" + ItemCode + "' and WhsCode = '" + WhsCode + "' ";
            return GF.GetSingleValue(dbType, lsSqlCommand, "OnHand");
        }

        private DataTable BuildFreight(DataTable dtFreight)
        {
            DataTable dt = new DataTable(TblLineName1);
            dt.Columns.Add("No");
            dt.Columns.Add("ExpnsCode");
            dt.Columns.Add("ExpnsName");
            dt.Columns.Add("Status");
            dt.Columns.Add("Comments");
            dt.Columns.Add("LineTotal");
            dt.Columns.Add("LineNum");
            dt.Columns.Add("DocEntry");

            if (dtFreight != null)
            {
                foreach (DataRow dr in dtFreight.Rows)
                {
                    DataRow row = dt.NewRow();
                    row["No"] = dr["No"];
                    row["ExpnsCode"] = dr["ExpnsCode"];
                    row["ExpnsName"] = dr["ExpnsName"];
                    row["Status"] = dr["Status"];
                    row["Comments"] = dr["Comments"];
                    row["LineTotal"] = dr["LineTotal"];
                    row["LineNum"] = dr["LineNum"];
                    row["DocEntry"] = dr["DocEntry"];
                    dt.Rows.Add(row);
                }
            }
            return dt;
        }

        /// <summary>
        /// 
        /// </summary>
        protected void LoadData(String sqId, string NewDocType)
        {
            string dbType = Session[Utils.AppConstants.ID_Dealer].ToString() == "VSM" ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER;
            GeneralFunctions GF = (GeneralFunctions)Session["SQGF"];

            Transaction ts = new Transaction();
            DataSet returnDoc = ts.GetMarketingDocument_ReturnDS(NewDocType, sqId, dbType);

            if (returnDoc == null) returnDoc = ts.GetMarketingDocument_ReturnDS(NewDocType, "1", dbType);
                        
            if (returnDoc == null || returnDoc.Tables.Count < 3)
            {
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('No record found!','');", true);
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading", "Dialog.hideLoader();", true);
                return;
            }

            DataTable dtHeader = returnDoc.Tables[0];
            DataRow dr = dtHeader.Rows[0];
            txtPostingDate.Text = String.Format("{0:dd/MM/yyyy}", Convert.ToDateTime(dr["DocDate"], new CultureInfo("es-US")));
            txtDocDate.Text = String.Format("{0:dd/MM/yyyy}", Convert.ToDateTime(dr["TaxDate"], new CultureInfo("es-US")));
            this.txtSQNo.Text = dr["DocNum"].ToString();
            this.txtCustomerCode.Text = dr["CardCode"].ToString();
            this.txtCustomerName.Text = dr["CardName"].ToString();
            this.txtContactPerson.Text = dr["U_ContactPerson"].ToString();
            this.txtRemarks.Text = dr["Comments"].ToString();
            this.lblOtherFees.Text = GF.FormatNumeric(GF.ResetFormatNumeric(string.IsNullOrEmpty(dr["TotalExpns"].ToString()) ? "0" : dr["TotalExpns"].ToString()), "SumDec");

            if (dr["DocStatus"].ToString().Equals("C"))
            {
                this.lblStatus.Text = "Closed";
                SetScreenStatus("Close");
            }
            else if (dr["DocStatus"].ToString().Equals("O"))
            {
                this.lblStatus.Text = "Open";
                SetScreenStatus("Update");
            }

            // Binding Sale Man 
            GF.BindDataSaleMan(dbType, Session[Utils.AppConstants.ID_Dealer].ToString(), ddlSaleMan, dr["SlpCode"].ToString());
            // Binding details
            DataTable dtContents = BuildContents(returnDoc.Tables[1]);
            foreach (DataRow row in dtContents.Rows)
            {
                row["ShipDate"] = Convert.ToDateTime((String.IsNullOrEmpty(row["ShipDate"].ToString()) ? DateTime.Now.ToString("dd/MM/yyyy") : row["ShipDate"].ToString())).ToString("dd/MM/yyyy");
                updateRowTotalPrice(row, "");
                if ( ConvertDocType.Get2String(DocType.SALES_QUOTATION) != NewDocType) //truong hop copy to
                {
                    row["BaseEntry"] = sqId;
                    row["BaseType"] = NewDocType;
                    row["BaseLine"] = row["LineNum"];
                }
            }
            // Get Freight Charge
            Session["FreightTable"] = returnDoc.Tables[2];

            BindData(dtContents);
            updateTableTotalPrice();
        }

        protected void LoadDefault()
        {
            this.lblStatus.Text = "Open";
            this.txtPostingDate.Text = DateTime.Now.ToString("dd/MM/yyyy");
            this.txtDocDate.Text = DateTime.Now.ToString("dd/MM/yyyy");
            this.txtSQNo.Text = 
            this.txtCustomerCode.Text = 
            this.txtCustomerName.Text = 
            this.txtContactPerson.Text = string.Empty;
            // Binding Sale Man 
            string dbType = Session[Utils.AppConstants.ID_Dealer].ToString() == "VSM" ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER;
            GeneralFunctions GF = (GeneralFunctions)Session["SQGF"];

            GF.BindDataSaleMan(dbType, Session[Utils.AppConstants.ID_Dealer].ToString(), ddlSaleMan, "-1");

            DataTable dtContents = BuildContents((DataTable)Session["SQTable"]);
            BindData(dtContents);
            // Build Freight Charge
            DataTable dtFreight = GF.GetFreightList(dbType);
            Session["FreightTable"] = BuildFreight(dtFreight);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="tblData"></param>
        private void BindData(DataTable tblData)
        {
            Session["SQTable"] = tblData;
            this.grvSQ.DataSource = tblData;
            this.grvSQ.DataBind();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void txtUnitPrice_OnTextChanged(object sender, EventArgs e)
        {
            try
            {
                this.lblError.Visible = false;
                GridViewRow row = (GridViewRow)((DataControlFieldCell)((TextBox)sender).Parent).Parent;
                ViewState["rowindex"] = row.RowIndex;
                TextBox txtUnitPrice = (TextBox)row.FindControl("txtUnitPrice");
                if (txtUnitPrice.Text.Trim().Length == 0)
                {
                    ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "CallJS", "alert('Pls input Price');", true);
                    txtUnitPrice.Focus();
                    return;
                }

                Label lblNo = (Label)row.FindControl("lblNo");
                DataTable tb = (DataTable)Session["SQTable"];

                if (tb != null)
                {
                    DataRow[] rupdate = tb.Select("No=" + lblNo.Text );
                    if (rupdate.Length > 0)
                    {
                        GeneralFunctions GF = (GeneralFunctions)Session["SQGF"];
                        rupdate[0]["PriceBefDi"] = GF.FormatNumeric(GF.ResetFormatNumeric(txtUnitPrice.Text), "SumDec");
                        updateRowTotalPrice(rupdate[0], "PriceBefDi");
                    }
                }

                this.grvSQ.EditIndex = -1;

                BindData(tb);
                //CalcTotal(tb);
                updateTableTotalPrice();
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void txtDiscount_OnTextChanged(object sender, EventArgs e)
        {
            try
            {
                this.lblError.Visible = false;
                GridViewRow row = (GridViewRow)((DataControlFieldCell)((TextBox)sender).Parent).Parent;
                ViewState["rowindex"] = row.RowIndex;
                TextBox txtDiscount = (TextBox)row.FindControl("txtDiscount");
                if (txtDiscount.Text.Trim().Length == 0)
                {
                    ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "CallJS", "alert('Pls input Discount');", true);
                    txtDiscount.Focus();
                    return;
                }

                Label lblNo = (Label)row.FindControl("lblNo");
                DataTable tb = (DataTable)Session["SQTable"];

                if (tb != null)
                {
                    DataRow[] rupdate = tb.Select("No=" + lblNo.Text );
                    if (rupdate.Length > 0)
                    {
                        GeneralFunctions GF = (GeneralFunctions)Session["SQGF"];
                        rupdate[0]["U_Discount"] = GF.FormatNumeric(GF.ResetFormatNumeric(txtDiscount.Text), "SumDec");
                        updateRowTotalPrice(rupdate[0], "U_Discount");
                    }
                }

                this.grvSQ.EditIndex = -1;

                BindData(tb);
                //CalcTotal(tb);
                updateTableTotalPrice();
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void txtIncentiveDsc_OnTextChanged(object sender, EventArgs e)
        {
            try
            {
                this.lblError.Visible = false;
                GridViewRow row = (GridViewRow)((DataControlFieldCell)((TextBox)sender).Parent).Parent;
                ViewState["rowindex"] = row.RowIndex;
                TextBox txtIncentiveDsc = (TextBox)row.FindControl("txtIncentiveDsc");
                if (txtIncentiveDsc.Text.Trim().Length == 0)
                {
                    ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "CallJS", "alert('Pls input Incentive Discount.');", true);
                    txtIncentiveDsc.Focus();
                    return;
                }

                Label lblNo = (Label)row.FindControl("lblNo");
                DataTable tb = (DataTable)Session["SQTable"];

                if (tb != null)
                {
                    DataRow[] rupdate = tb.Select("No=" + lblNo.Text );
                    if (rupdate.Length > 0)
                    {
                        GeneralFunctions GF = (GeneralFunctions)Session["SQGF"];
                        rupdate[0]["U_IncentiveDiscount"] = GF.FormatNumeric(GF.ResetFormatNumeric(txtIncentiveDsc.Text), "SumDec");
                        updateRowTotalPrice(rupdate[0], "U_IncentiveDiscount");
                    }
                }

                this.grvSQ.EditIndex = -1;

                BindData(tb);
                //CalcTotal(tb);
                updateTableTotalPrice();
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void txtShipDate_OnTextChanged(object sender, EventArgs e)
        {
            try
            {
                this.lblError.Visible = false;
                GridViewRow row = (GridViewRow)((DataControlFieldCell)((TextBox)sender).Parent).Parent;
                ViewState["rowindex"] = row.RowIndex;
                TextBox txtShipDate = (TextBox)row.FindControl("txtShipDate");
                if (txtShipDate.Text.Trim().Length == 0)
                {
                    ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "CallJS", "alert('Pls input Ship Date');", true);
                    txtShipDate.Focus();
                    return;
                }
                Label lblNo = (Label)row.FindControl("lblNo");
                DataTable tb = (DataTable)Session["SQTable"];
                if (tb != null)
                {
                    DataRow[] rupdate = tb.Select("No=" + lblNo.Text);
                    if (rupdate.Length > 0)
                    {
                        rupdate[0]["ShipDate"] = txtShipDate.Text;
                    }
                }

                this.grvSQ.EditIndex = -1;

                BindData(tb);
                updateTableTotalPrice();
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="e"></param>
        protected override void OnLoadComplete(EventArgs e)
        {
            try
            {
                base.OnLoadComplete(e);
                if (this.Request["__EVENTARGUMENT"] != null && this.Request["__EVENTARGUMENT"].ToString() != "")
                {
                    DateTime poDate = Utils.AppConstants.ConvertToDate(this.txtPostingDate.Text);
                    DataTable tblSQ = (DataTable)Session["SQTable"];
                    string dbType = Session[Utils.AppConstants.ID_Dealer].ToString() == "VSM" ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER;

                    switch (this.Request["__EVENTARGUMENT"].ToString())
                    {
                        case "SelectItem":
                            this.lblError.Visible = false;
                            if (tblSQ != null)
                            {
                                Dictionary<string, string> dicItem = Session["ChosenItem"] != null ? (Dictionary<string, string>)Session["ChosenItem"] : null;
                                if (dicItem != null)
                                {
                                    foreach (KeyValuePair<string, string> item in dicItem)
                                    {
                                        DataRow rowNew = tblSQ.NewRow();
                                        rowNew["No"] = (tblSQ.Rows.Count + 1).ToString();
                                        rowNew["ItemCode"] = item.Key;
                                        rowNew["Dscription"] = item.Value;
                                        rowNew["U_Model"] = 
                                        rowNew["U_Product"] =
                                        rowNew["U_Color"] = string.Empty;
                                        rowNew["Quantity"] = 1;
                                        //rowNew["PriceBefDi"] = 0;
                                        //rowNew["DiscPrcnt"] = 0;
                                        rowNew["PriceBefDi"] = 0;
                                        DataTable dtVatGroup = (DataTable)Session["SQdtVatGroup"];
                                        rowNew["VatGroup"] = dtVatGroup.Rows.Count > 0 ? dtVatGroup.Rows[0]["Code"].ToString() : string.Empty;
                                        rowNew["VatPrcnt"] = dtVatGroup.Rows.Count > 0 ? dtVatGroup.Rows[0]["Rate"].ToString() : "0";
                                        rowNew["VatSum"] =
                                        rowNew["U_Discount"] =
                                        rowNew["U_IncentiveDiscount"] = 0;
                                        DataTable dtWhs = (DataTable)Session["SQdtWhs"];
                                        rowNew["WhsCode"] = dtWhs.Rows.Count > 0 ? dtWhs.Rows[0]["WhsCode"].ToString() : string.Empty;

                                        tblSQ.Rows.Add(rowNew);
                                    }

                                    if (tblSQ.Rows.Count > 0)
                                        foreach (DataRow dr in tblSQ.Rows)
                                            updateRowTotalPrice(dr, ""); 
                                }
                            }
                            //ReLoad Data
                            BindData(tblSQ);
                            updateTableTotalPrice();
                            break;

                        case "SelectBP":
                            ViewState["rowindex"] = -1;
                            this.lblError.Visible = false;
                            GridViewRow row = Session["ChosenBP"] != null ? (GridViewRow)Session["ChosenBP"] : null;
                            this.txtCustomerCode.Text = ((Label)row.FindControl("lblCardCode")).Text;
                            this.txtCustomerName.Text = ((Label)row.FindControl("lblCardName")).Text;
                            this.txtContactPerson.Text = ((Label)row.FindControl("lblCntctPrsn")).Text;
                            if (tblSQ != null) tblSQ.Rows.Clear();
                            Session["ChosenBP"] = null;
                            this.btnAddItems.Enabled = true;
                            this.btnAddAccessories.Enabled = true;
                            break;

                        case "SelectDocList":
                            GridViewRow rowDocList = Session["ChosenDocList"] != null ? (GridViewRow)Session["ChosenDocList"] : null;
                            string sqId = ((Label)rowDocList.FindControl("lblDocNum")).Text;
                            Response.Redirect(CurrentPageUrl + "?sq_id=" + sqId);
                            break;

                        case "AddFreight":
                            // Update Freight Amount
                            GeneralFunctions GF = (GeneralFunctions)Session["SQGF"];
                            DataTable dtQUT3 = (DataTable)Session["FreightTable"];
                            Double dblAmount = 0;
                            foreach (DataRow dr in dtQUT3.Rows)
                            {
                                
                                string lsAmount = GF.ResetFormatNumeric(dr["LineTotal"].ToString());
                                dblAmount += Double.Parse(string.IsNullOrEmpty(lsAmount) ? "0" : lsAmount);
                            }
                            lblOtherFees.Text = GF.FormatNumeric(dblAmount.ToString(), "SumDec");
                            updateTableTotalPrice();
                            break;

                        default:
                            break;
                    }
                }
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
        }
 
        /// <summary>
        /// 
        /// </summary>
        private void UpdatePrice()
        {
            try
            {  
                BindData((DataTable)Session["SQTable"]);
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
        }

        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void grvSQ_RowCreated(object sender, GridViewRowEventArgs e)
        {
            // this is VSM --> disable Dealer Stock
            if (Session[Utils.AppConstants.ID_Dealer].ToString().Equals(Utils.AppConstants.VSM)) grvSQ.Columns[18].Visible = false;

            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                GridViewRow myRow = e.Row;
                Label lblNo = myRow.FindControl("lblNo") as Label;
                lblNo.Text = (myRow.RowIndex + 1).ToString();

                if (this.hdnStatus.Value == "C")
                {
                    TextBox txtQuantity = (TextBox)myRow.FindControl("txtOrderQuantity");
                    TextBox txtUnitPrice = (TextBox)myRow.FindControl("txtUnitPrice");
                    TextBox txtDiscount = (TextBox)myRow.FindControl("txtDiscount");
                    TextBox txtIncentiveDsc = (TextBox)myRow.FindControl("txtIncentiveDsc");

                    TextBox txtShipDate = (TextBox)myRow.FindControl("txtShipDate");
                    ImageButton imgShipDate = (ImageButton)myRow.FindControl("imgShipDate");

                    LinkButton lnkDelete = (LinkButton)myRow.FindControl("lnkDelete");
                    if (lnkDelete != null) lnkDelete.Enabled = false;

                    if (txtQuantity != null)
                    {
                        txtQuantity.ReadOnly = true;
                        txtQuantity.BorderStyle = BorderStyle.None;
                        txtQuantity.BackColor = System.Drawing.Color.Transparent;
                    }
                    if (txtUnitPrice != null)
                    {
                        txtUnitPrice.ReadOnly = true;
                        txtUnitPrice.BorderStyle = BorderStyle.None;
                        txtUnitPrice.BackColor = System.Drawing.Color.Transparent;
                    }
                    if (txtDiscount != null)
                    {
                        txtDiscount.ReadOnly = true;
                        txtDiscount.BorderStyle = BorderStyle.None;
                        txtDiscount.BackColor = System.Drawing.Color.Transparent;
                    }

                    if (txtShipDate != null)
                    {
                        txtShipDate.ReadOnly = true;
                        txtShipDate.BackColor = System.Drawing.Color.Transparent;
                        txtShipDate.BorderStyle = BorderStyle.None;
                    }

                    if (txtIncentiveDsc != null)
                    {
                        txtIncentiveDsc.ReadOnly = true;
                        txtIncentiveDsc.BorderStyle = BorderStyle.None;
                        txtIncentiveDsc.BackColor = System.Drawing.Color.Transparent;
                    }
                }
                else if(!Session[Utils.AppConstants.ID_Dealer].ToString().Equals(Utils.AppConstants.VSM))
                {
                    TextBox txtUnitPrice = (TextBox)myRow.FindControl("txtUnitPrice");
                    if (txtUnitPrice != null)
                    {
                        txtUnitPrice.ReadOnly = true;
                        txtUnitPrice.BorderStyle = BorderStyle.None;
                        txtUnitPrice.BackColor = System.Drawing.Color.Transparent;
                    }
                }
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void txtPODate_TextChanged(object sender, EventArgs e)
        {
            try
            {
                //Check Valid Date
               Utils.AppConstants.ConvertToDate(this.txtPostingDate.Text.Trim());
                this.btnAddItems.Enabled = true;
            }
            catch
            {
                this.btnAddItems.Enabled = false;
            }
            UpdatePrice();
        }
        /// <summary>
        /// 
        /// </summary>
 
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                string dbType = Session[Utils.AppConstants.ID_Dealer].ToString() == "VSM" ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER;

                if (string.IsNullOrEmpty(txtPostingDate.Text))
                {
                    ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('Missing Posting Date.','');", true);
                    ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading", "Dialog.hideLoader();", true);
                    return;
                }

                if (string.IsNullOrEmpty(txtDocDate.Text))
                {
                    ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('Missing Document Date.','');", true);
                    ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading", "Dialog.hideLoader();", true);
                    return;
                }

                if (string.IsNullOrEmpty(txtCustomerCode.Text))
                {
                    ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('Missing Customer Code.','');", true);
                    ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading", "Dialog.hideLoader();", true);
                    return;
                }

                String requestXML = _collectData();
                if (string.IsNullOrEmpty(requestXML)) return;

                Transaction ts = new Transaction();
                DataSet ds = ts.CreateMarketingDocument(requestXML, ConvertDocType.Get2String(DocType.SALES_QUOTATION), txtSQNo.Text, hdnIsUpdate.Value.Equals("true"), dbType);

                if ((int)ds.Tables[0].Rows[0]["ErrCode"] != 0)
                {
                    Session["errorMessage"] = ds.Tables[0].Rows[0]["ErrMsg"];
                    Session["requestXML"] = requestXML;
                    ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('" + GeneralFunctions.UrlFullEncode(ds.Tables[0].Rows[0]["ErrMsg"].ToString()) + "','');", true);
                }
                else
                {
                    Session["successMessage"] = "Operation complete sucessful!";
                    ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('" + "Operation complete sucessful!" + "','');", true);
                    ClearScreen();
                }
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading", "Dialog.hideLoader();", true);
                //SetControlsStatus("Save");
            }
            catch (Exception ex)
            {
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('" + ex.ToString() + "','');", true);
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading", "Dialog.hideLoader();", true);
            } 
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnCancel_Click(object sender, EventArgs e)
        {
            CloseCancel(true);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="isClose"></param>
        private void CloseCancel(bool isClose)
        {
            try
            {
                Transaction ts = new Transaction();
                string dbType = Session[Utils.AppConstants.ID_Dealer].ToString().Equals(Utils.AppConstants.VSM) ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER;
                DataSet ds = ts.CloseCancelDocument(ConvertDocType.Get2String(DocType.SALES_QUOTATION), txtSQNo.Text, isClose, dbType);

                if ((int)ds.Tables[0].Rows[0]["ErrCode"] != 0)
                {
                    Session["errorMessage"] = ds.Tables[0].Rows[0]["ErrMsg"];
                    ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('" + GeneralFunctions.UrlFullEncode(ds.Tables[0].Rows[0]["ErrMsg"].ToString()) + "','');", true);
                }
                else
                {
                    Session["successMessage"] = "Operation complete sucessful!";
                    ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('" + "Operation complete sucessful!" + "','');", true);
                    ClearScreen();
                }
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading", "Dialog.hideLoader();", true);
            }
            catch (Exception ex)
            {
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('" + ex.ToString() + "','');", true);
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading", "Dialog.hideLoader();", true);
            }
        }

        public String _collectData()
        {
            try
            {
                GeneralFunctions GF = (GeneralFunctions)Session["SQGF"];
                //Update table header
                DataTable dtHeader = new DataTable(TblHeaderName);
                dtHeader.Columns.Add("DocEntry"); // key
                dtHeader.Columns.Add("DocNum"); // 
                dtHeader.Columns.Add("Series"); // 14
                dtHeader.Columns.Add("DocStatus");
                dtHeader.Columns.Add("DocDate");
                dtHeader.Columns.Add("TaxDate");
                dtHeader.Columns.Add("CardCode");
                dtHeader.Columns.Add("CardName");
                dtHeader.Columns.Add("Comments");
                dtHeader.Columns.Add("SlpCode");
                dtHeader.Columns.Add("GrosProfit");
                dtHeader.Columns.Add("VatSum");
                dtHeader.Columns.Add("TotalExpns");
                dtHeader.Columns.Add("DiscPrcnt");
                dtHeader.Columns.Add("DiscSum");
                dtHeader.Columns.Add("Address");
                // UDF
                dtHeader.Columns.Add("U_ContactPerson");
                dtHeader.Columns.Add("U_DealerID");
                dtHeader.Columns.Add("U_Department");


                DataRow drHeader = dtHeader.NewRow();
                if (hdnIsUpdate.Value.Equals("true"))
                {
                    drHeader["DocEntry"] = 
                    drHeader["DocNum"] = int.Parse(txtSQNo.Text);
                }
                else
                {
                    drHeader["Series"] = 14;
                    drHeader["DocStatus"] = "O";
                }
                drHeader["DocDate"] = Utils.AppConstants.ConvertToDate(txtPostingDate.Text).ToString("yyyyMMdd");
                drHeader["TaxDate"] = Utils.AppConstants.ConvertToDate(txtDocDate.Text).ToString("yyyyMMdd");
                drHeader["Comments"] = txtRemarks.Text;
                //dr["JrnlMemo"] = txtJournalRemark.Text;
                drHeader["CardCode"] = txtCustomerCode.Text;
                drHeader["CardName"] = txtCustomerName.Text;
                drHeader["SlpCode"] = ddlSaleMan.SelectedValue;
                drHeader["GrosProfit"] = GF.ResetFormatNumeric(string.IsNullOrEmpty(lblSubTotal.Text) ? "0" : lblSubTotal.Text);
                drHeader["VatSum"] = GF.ResetFormatNumeric(string.IsNullOrEmpty(lblTaxAmount.Text) ? "0" : lblTaxAmount.Text);
                drHeader["TotalExpns"] = GF.ResetFormatNumeric(string.IsNullOrEmpty(lblOtherFees.Text) ? "0" : lblOtherFees.Text);
                drHeader["Address"] = txtShipTo.Text.Trim();
                
                //drHeader["DiscPrcnt"] = 0.397456;
                //drHeader["DiscSum"] = 1500000;
                // UDF
                drHeader["U_ContactPerson"] = txtContactPerson.Text.Trim();
                drHeader["U_DealerID"] = Session[Utils.AppConstants.ID_Dealer].ToString();
                drHeader["U_Department"] = Utils.AppConstants.SALES;
                updateDiscPrcnt(drHeader); // Assign disc. prcnt and disc amount in Header.

                dtHeader.Rows.Add(drHeader);
                Array arrContentsCols = new string[] { "Quantity", "PriceBefDi", "Price", "VatSum", "U_Discount", "U_IncentiveDiscount", "LineTotal" }; // Columns need to reset format numeric

                DocumentXML objInfo = new DocumentXML();
                DataSet ds = new DataSet("DS");
                dtHeader.TableName = TblHeaderName;
                ds.Tables.Add(dtHeader.Copy());

                DataTable dtContents = (DataTable)Session["SQTable"];                
                DataTable dt = new DataTable(TblLineName);
                dt.Columns.Add("DocEntry");
                dt.Columns.Add("LineNum");
                dt.Columns.Add("LineStatus");
                dt.Columns.Add("ItemCode");
                dt.Columns.Add("Dscription");
                dt.Columns.Add("Quantity");
                dt.Columns.Add("ShipDate");
                dt.Columns.Add("Price");
                dt.Columns.Add("WhsCode");
                dt.Columns.Add("LineTotal");

                dt.Columns.Add("PriceBefDi");
                dt.Columns.Add("VatGroup");
                dt.Columns.Add("VatPrcnt");
                dt.Columns.Add("U_Color");
                dt.Columns.Add("U_Model");
                dt.Columns.Add("U_Product");
                //
                dt.Columns.Add("VatSum");
                dt.Columns.Add("U_Discount");
                dt.Columns.Add("U_IncentiveDiscount");

                int liNo = 0;
                foreach (DataRow dr in dtContents.Rows)
                {
                    DataRow rowNew = dt.NewRow();
                    if (hdnIsUpdate.Value.Equals("true")) rowNew["DocEntry"] = int.Parse(txtSQNo.Text);
                    rowNew["LineNum"] = liNo;
                    rowNew["LineStatus"] = "O";
                    rowNew["ItemCode"] = dr["ItemCode"];
                    rowNew["Dscription"] = dr["Dscription"];
                    rowNew["Quantity"] = dr["Quantity"];
                    rowNew["ShipDate"] = Utils.AppConstants.ConvertToDate(dr["ShipDate"].ToString().Substring(0, 10)).ToString("yyyyMMdd");
                    rowNew["Price"] = dr["Price"];
                    //rowNew["DiscPrcnt"] = dr["DiscPrcnt"];
                    rowNew["LineTotal"] = dr["LineTotal"];
                    rowNew["PriceBefDi"] = dr["PriceBefDi"];
                    rowNew["VatSum"] = dr["VatSum"];
                    rowNew["VatGroup"] = dr["VatGroup"];
                    rowNew["VatPrcnt"] = dr["VatPrcnt"];
                    rowNew["WhsCode"] = dr["WhsCode"];
                    rowNew["U_Discount"] = dr["U_Discount"];
                    rowNew["U_IncentiveDiscount"] = dr["U_IncentiveDiscount"];

                    rowNew["U_Color"] = dr["U_Color"];
                    rowNew["U_Model"] = dr["U_Model"];
                    rowNew["U_Product"] = dr["U_Product"];
                    dt.Rows.Add(rowNew);
                    liNo++;
                }
                ds.Tables.Add(GF.ResetFormatNumeric(dt, arrContentsCols).Copy());

                // Build Freight Charge
                DataTable dtQUT3 = new DataTable(TblLineName1);
                dtQUT3.Columns.Add("DocEntry");
                dtQUT3.Columns.Add("LineNum");
                dtQUT3.Columns.Add("ExpnsCode");
                dtQUT3.Columns.Add("Status");
                dtQUT3.Columns.Add("Comments");
                dtQUT3.Columns.Add("LineTotal");

                DataTable tblQUT3 = (DataTable)Session["FreightTable"];
                //liNo = 0;
                if(tblQUT3 != null)
                    foreach (DataRow dr in tblQUT3.Rows)
                    {
                        DataRow rowNew = dtQUT3.NewRow();
                        if (hdnIsUpdate.Value.Equals("true")) rowNew["DocEntry"] = int.Parse(txtSQNo.Text);
                        rowNew["LineNum"] = dr["LineNum"];
                        rowNew["ExpnsCode"] = dr["ExpnsCode"];
                        rowNew["Status"] = "O";
                        rowNew["Comments"] = dr["Comments"];
                        rowNew["LineTotal"] = GF.ResetFormatNumeric(dr["LineTotal"].ToString());
                        dtQUT3.Rows.Add(rowNew);
                        //liNo++;
                    }
                ds.Tables.Add(dtQUT3.Copy());
                return objInfo.ToXMLStringFromDS(ConvertDocType.Get2String(DocType.SALES_QUOTATION), ds);
            }
            catch (Exception ex)
            {
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('" + ex.ToString() + "','');", true);
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading", "Dialog.hideLoader();", true);
                return "";
            }
        }

        protected void ClearScreen()
        {
            // Binding Sale Man 
            string dbType = Session[Utils.AppConstants.ID_Dealer].ToString() == "VSM" ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER;
            GeneralFunctions GF = new GeneralFunctions(dbType, Session[Utils.AppConstants.ID_Dealer].ToString());

            GF.BindDataSaleMan(dbType, Session[Utils.AppConstants.ID_Dealer].ToString(), ddlSaleMan, "-1");
            // Reset session
            Session["SQTable"] = 
            //Session["SQGF"] = 
            //Session["SQdtWhs"] = 
            //Session["SQdtVatGroup"] = 
            Session["FreightTable"] = null;

            CultureInfo ci = System.Threading.Thread.CurrentThread.CurrentCulture;
            this.txtPostingDate.Text.ToString(ci);
            this.txtDocDate.Text.ToString(ci);
            txtSQNo.Text = 
            this.txtCustomerCode.Text =
            this.txtCustomerName.Text = 
            this.txtRemarks.Text = 
            this.txtContactPerson.Text = string.Empty;

            this.lblTaxAmount.Text = 
            this.lblSubTotal.Text = 
            this.lblPaymentTotal.Text = 
            this.lblOtherFees.Text = "0";

            txtShipTo.Text = GF.GetSingleValue(dbType, "select Address from OCRD where CardCode = '" + Session[Utils.AppConstants.ID_Dealer].ToString() + "'", "Address");

            // Get details SQ
            DataTable dtContents = BuildContents((DataTable)Session["SQTable"]);
            BindData(dtContents);

            // Build Freight Charge
            DataTable dtFreight = GF.GetFreightList(dbType);
            Session["FreightTable"] = BuildFreight(dtFreight);
            SetScreenStatus("New");    
        }

        protected void SetScreenStatus(string Status)
        {
            switch (Status)
            {
                case "New":
                    btnAddItems.Enabled = 
                    btnAddAccessories.Enabled = 
                    btnPrint.Enabled = 
                    btnCopy.Enabled = false;
                    btnSelectBP.Enabled = 
                    btnSave.Enabled = 
                    btnCancel.Enabled = true;
                    hdnIsUpdate.Value = "false";
                    hdnStatus.Value = "O";
                    break;

                case "Update":
                    btnSelectBP.Enabled =
                    btnAddItems.Enabled =
                    btnAddAccessories.Enabled =
                    btnSave.Enabled =
                    btnCancel.Enabled =
                    btnPrint.Enabled = 
                    btnCopy.Enabled = true;
                    hdnIsUpdate.Value = "true";
                    hdnStatus.Value = "O";
                    break;

                case "Close":
                    btnSelectBP.Enabled = 
                    btnAddItems.Enabled = 
                    btnAddAccessories.Enabled = 
                    btnSave.Enabled =
                    btnCancel.Enabled = 
                    btnCopy.Enabled = false;
                    btnPrint.Enabled = true;
                    hdnStatus.Value = "C";
                    break;
            }
        }

        protected void btnCopy_Click(object sender, EventArgs e)
        {
            Response.Redirect(TargetPageUrl + "?base_type=" + ConvertDocType.Get2String(DocType.SALES_QUOTATION) + "&base_entry=" + txtSQNo.Text);
        }

        protected void btnLastRecord_Click(object sender, EventArgs e)
        {
            string dbType = Session[Utils.AppConstants.ID_Dealer].ToString() == "VSM" ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER;
            GetDefault fGetDefault = new GetDefault();
            string lsSQNo = fGetDefault.GetMaxDocEntry(
                dbType, 
                Session[Utils.AppConstants.ID_Dealer].ToString(), 
                Utils.AppConstants.SALES, 
                ConvertDocType.Get2String(DocType.SALES_QUOTATION), 
                TblHeaderName, HeaderKeyName
            );
            if(txtSQNo.Text.CompareTo(lsSQNo) != 0)
                Response.Redirect(CurrentPageUrl + "?sq_id=" + lsSQNo);
        }

        protected void ddlModel_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                this.lblError.Visible = false;
                GridViewRow row = (GridViewRow)((DataControlFieldCell)((DropDownList)sender).Parent).Parent;
                ViewState["rowindex"] = row.RowIndex;
                DropDownList ddlModel = (DropDownList)row.FindControl("ddlModel");
                if (ddlModel.SelectedValue.Trim().Length == 0)
                {
                    ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "CallJS", "alert('Pls selection a Model');", true);
                    ddlModel.Focus();
                    return;
                }
                Label txtModel = (Label)row.FindControl("txtModel");
                txtModel.Text = ddlModel.SelectedValue;

                // Load Product
                DropDownList ddlProduct = (DropDownList)row.FindControl("ddlProduct");
                if (ddlProduct != null)
                {
                    string dbType = Session[Utils.AppConstants.ID_Dealer].ToString() == "VSM" ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER;
                    GeneralFunctions GF = (GeneralFunctions)Session["SQGF"];
                    ddlProduct.DataSource = GF.GetProductByModel(dbType, ddlModel.SelectedValue);
                    ddlProduct.DataValueField = "Code";
                    ddlProduct.DataTextField = "Name";
                    ddlProduct.DataBind();
                    ddlProduct.Items.Insert(0, "");

                    Label txtProduct = (Label)row.FindControl("txtProduct");
                    txtProduct.Text = ddlProduct.SelectedValue;
                    SetItem(row);
                }
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
        }

        protected void ddlProduct_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                this.lblError.Visible = false;
                GridViewRow row = (GridViewRow)((DataControlFieldCell)((DropDownList)sender).Parent).Parent;
                ViewState["rowindex"] = row.RowIndex;
                DropDownList ddlProduct = (DropDownList)row.FindControl("ddlProduct");
                if (ddlProduct.SelectedValue.Trim().Length == 0)
                {
                    ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "CallJS", "alert('Pls selection a Product');", true);
                    ddlProduct.Focus();
                    return;
                }

                Label txtProduct = (Label)row.FindControl("txtProduct");
                txtProduct.Text = ddlProduct.SelectedValue;
                SetItem(row);
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
        }

        protected void ddlColor_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                this.lblError.Visible = false;
                GridViewRow row = (GridViewRow)((DataControlFieldCell)((DropDownList)sender).Parent).Parent;
                ViewState["rowindex"] = row.RowIndex;
                DropDownList ddlColor = (DropDownList)row.FindControl("ddlColor");
                if (ddlColor.SelectedValue.Trim().Length == 0)
                {
                    ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "CallJS", "alert('Pls selection a Color');", true);
                    ddlColor.Focus();
                    return;
                }

                Label txtCorlor = (Label)row.FindControl("txtCorlorCode");
                txtCorlor.Text = ddlColor.SelectedValue;
                SetItem(row);
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
        }

        protected void ddlWhs_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                this.lblError.Visible = false;
                GridViewRow row = (GridViewRow)((DataControlFieldCell)((DropDownList)sender).Parent).Parent;
                ViewState["rowindex"] = row.RowIndex;
                DropDownList ddlWhs = (DropDownList)row.FindControl("ddlWhs");
                if (ddlWhs.SelectedValue.Trim().Length == 0)
                {
                    ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "CallJS", "alert('Pls selection a warehouse');", true);
                    ddlWhs.Focus();
                    return;
                }

                HiddenField hdnWhsCode = (HiddenField)row.FindControl("hdnWhsCode");
                if (hdnWhsCode != null && !string.IsNullOrEmpty(hdnWhsCode.Value))
                {
                    hdnWhsCode.Value = ddlWhs.SelectedValue;
                    DataTable tblQUT1 = (DataTable)Session["SQTable"];
                    Label lblNo = (Label)row.FindControl("lblNo");
                    DataRow[] rowUpdate = tblQUT1.Select("No=" + lblNo.Text);
                    if (rowUpdate.Length > 0)
                    {
                        rowUpdate[0]["WhsCode"] = hdnWhsCode.Value;
                        rowUpdate[0]["OnHand"] = GetDealerOnHandQty(rowUpdate[0]["ItemCode"].ToString(), hdnWhsCode.Value);
                    }
                    BindData(tblQUT1);
                }
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
        }

        protected void ddlVatGroup_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                this.lblError.Visible = false;
                GridViewRow row = (GridViewRow)((DataControlFieldCell)((DropDownList)sender).Parent).Parent;
                ViewState["rowindex"] = row.RowIndex;
                DropDownList ddlVatGroup = (DropDownList)row.FindControl("ddlVatGroup");
                if (ddlVatGroup.SelectedValue.Trim().Length == 0)
                {
                    ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "CallJS", "alert('Pls selection a Tax Code.');", true);
                    ddlVatGroup.Focus();
                    return;
                }

                HiddenField hdnVatGroup = (HiddenField)row.FindControl("hdnVatGroup");
                if (hdnVatGroup != null && !string.IsNullOrEmpty(hdnVatGroup.Value))
                {
                    hdnVatGroup.Value = ddlVatGroup.SelectedValue;
                    DataTable tblQUT1 = (DataTable)Session["SQTable"];
                    Label lblNo = (Label)row.FindControl("lblNo");
                    //
                    DataRow[] rowUpdate = tblQUT1.Select("No=" + lblNo.Text);
                    if (rowUpdate.Length > 0)
                    {
                        rowUpdate[0]["VatGroup"] = hdnVatGroup.Value;
                        DataTable dtVatGroup = (DataTable)Session["SQdtVatGroup"];
                        DataRow[] rRate = dtVatGroup.Select("Code='" + hdnVatGroup.Value + "'");
                        if (rRate.Length > 0)
                        {
                            HiddenField hdnVatPrcnt = (HiddenField)row.FindControl("hdnVatPrcnt");
                            if (hdnVatPrcnt != null) hdnVatPrcnt.Value = rRate[0]["Rate"].ToString();
                            rowUpdate[0]["VatPrcnt"] = rRate[0]["Rate"];
                            updateRowTotalPrice(rowUpdate[0], "");
                        }
                    }

                    BindData(tblQUT1);
                    updateTableTotalPrice(); // Update Grand Total
                }
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
        }

        private void SetItem(GridViewRow row)
        {
            DataTable tblQUT1 = (DataTable)Session["SQTable"];
            Label lblNo = (Label)row.FindControl("lblNo");
            DropDownList ddlModel = (DropDownList)row.FindControl("ddlModel");
            DropDownList ddlProduct = (DropDownList)row.FindControl("ddlProduct");
            DropDownList ddlCorlor = (DropDownList)row.FindControl("ddlColor");

            if (ddlModel != null && ddlProduct != null && ddlCorlor != null)
            {
                string dbType = Session[Utils.AppConstants.ID_Dealer].ToString() == "VSM" ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER;
                GeneralFunctions GF = (GeneralFunctions)Session["SQGF"];
                DataTable dtItem = GF.GetItem(dbType, Session[Utils.AppConstants.ID_Dealer].ToString(), ddlModel.SelectedValue, ddlProduct.SelectedValue, ddlCorlor.SelectedValue);
                GetDefault defaultWS = new GetDefault();
                DataRow[] rowUpdate = null;
                if (dtItem != null && dtItem.Rows.Count == 1)
                {
                    DateTime poDate = Utils.AppConstants.ConvertToDate(this.txtPostingDate.Text);
                    DataSet defaultInfo = defaultWS.GetDefaultLineInfo(dbType, Session[Utils.AppConstants.ID_Dealer].ToString(),
                        this.txtCustomerCode.Text, dtItem.Rows[0]["ItemCode"].ToString(), 1, poDate, Utils.AppConstants.SALES);
                    if (defaultInfo != null && defaultInfo.Tables != null && defaultInfo.Tables[0].Rows.Count == 1)
                    {
                        DataRow drDefaultLine = defaultInfo.Tables[0].Rows[0];
                        rowUpdate = tblQUT1.Select("No=" + lblNo.Text);
                        if (rowUpdate.Length == 1)
                        {
                            rowUpdate[0]["ItemCode"] = dtItem.Rows[0]["ItemCode"].ToString();
                            rowUpdate[0]["Dscription"] = dtItem.Rows[0]["ItemName"].ToString();
                            rowUpdate[0]["U_Model"] = ddlModel.SelectedValue;
                            rowUpdate[0]["U_Product"] = ddlProduct.SelectedValue;
                            rowUpdate[0]["U_Color"] = ddlCorlor.SelectedValue;
                            rowUpdate[0]["Quantity"] = 1;

                            //rowUpdate[0]["PriceBefDi"] = drDefaultLine["UnitPrice"];
                            //rowUpdate[0]["DiscPrcnt"] = drDefaultLine["Discount"];
                            rowUpdate[0]["PriceBefDi"] = drDefaultLine["PriceAfDi"];

                            rowUpdate[0]["VatGroup"] = drDefaultLine["TaxCode"];
                            rowUpdate[0]["VatPrcnt"] = drDefaultLine["TaxRate"];
                            rowUpdate[0]["VatSum"] = 0;
                            rowUpdate[0]["WhsCode"] = drDefaultLine["WhsCode"];

                            rowUpdate[0]["OnHand"] = GetDealerOnHandQty(dtItem.Rows[0]["ItemCode"].ToString(), drDefaultLine["WhsCode"].ToString());
                            rowUpdate[0]["OnHand_VSM"] = GetVSMOnHandQty(dtItem.Rows[0]["ItemCode"].ToString());
                            rowUpdate[0]["Available"] = GetAvailableQty(dtItem.Rows[0]["ItemCode"].ToString());

                            updateRowTotalPrice(rowUpdate[0], "");
                        }    
                    }
                }
                else
                {
                    rowUpdate = tblQUT1.Select("No=" + lblNo.Text);
                    rowUpdate[0]["ItemCode"] = 
                    rowUpdate[0]["Dscription"] = string.Empty;
                    rowUpdate[0]["U_Model"] = ddlModel.SelectedValue;
                    rowUpdate[0]["U_Product"] = ddlProduct.SelectedValue;
                    rowUpdate[0]["U_Color"] = ddlCorlor.SelectedValue;
                    rowUpdate[0]["Quantity"] = 1;

                    //rowUpdate[0]["PriceBefDi"] = 0;
                    //rowUpdate[0]["DiscPrcnt"] = 0;
                    rowUpdate[0]["PriceBefDi"] = 0;
                    DataTable dtVatGroup = (DataTable)Session["SQdtVatGroup"];
                    rowUpdate[0]["VatGroup"] = dtVatGroup.Rows.Count > 0 ? dtVatGroup.Rows[0]["Code"].ToString() : string.Empty;
                    rowUpdate[0]["VatPrcnt"] = dtVatGroup.Rows.Count > 0 ? dtVatGroup.Rows[0]["Rate"].ToString() : "0";
                    rowUpdate[0]["VatSum"] = 0;
                    DataTable dtWhs = (DataTable)Session["SQdtWhs"];
                    rowUpdate[0]["WhsCode"] = dtWhs.Rows.Count > 0 ? dtWhs.Rows[0]["WhsCode"].ToString() : string.Empty;
                    rowUpdate[0]["OnHand"] = 
                    rowUpdate[0]["OnHand_VSM"] =
                    rowUpdate[0]["Available"] = 0;
                    updateRowTotalPrice(rowUpdate[0], "");
                }
                BindData(tblQUT1);
                updateTableTotalPrice();
            }
        }

        protected void btnAddItems_Click(object sender, EventArgs e)
        {
            DataTable tbQUT1 = (DataTable)Session["SQTable"];
            DataRow rowNew = tbQUT1.NewRow();
            rowNew["No"] = (tbQUT1.Rows.Count + 1).ToString();
            rowNew["ItemCode"] = 
            rowNew["Dscription"] = 
            rowNew["U_Model"] = 
            rowNew["U_Product"] = 
            rowNew["U_Color"] = string.Empty;
            rowNew["Quantity"] = 1;
            rowNew["ShipDate"] = DateTime.Now.ToString("dd/MM/yyyy");
            //rowNew["PriceBefDi"] = 0;
            //rowNew["DiscPrcnt"] = 0;
            rowNew["PriceBefDi"] = 0;
            DataTable dtVatGroup = (DataTable)Session["SQdtVatGroup"];
            rowNew["VatGroup"] = dtVatGroup.Rows.Count > 0 ? dtVatGroup.Rows[0]["Code"].ToString() : string.Empty;
            rowNew["VatPrcnt"] = dtVatGroup.Rows.Count > 0 ? dtVatGroup.Rows[0]["Rate"].ToString() : "0";
            rowNew["VatSum"] = 
            rowNew["U_Discount"] = 
            rowNew["U_IncentiveDiscount"] = 0;
            DataTable dtWhs = (DataTable)Session["SQdtWhs"];
            rowNew["WhsCode"] = dtWhs.Rows.Count > 0 ? dtWhs.Rows[0]["WhsCode"].ToString() : string.Empty;
            tbQUT1.Rows.Add(rowNew);
            BindData(tbQUT1);
        }

        protected void lnkFreight_Click(object sender, EventArgs e)
        {
            try
            {
                string popup = "OpenFreight()";
                ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "CallJS", popup, true);
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
        }

        protected void lblVSMAvailable_Click(object sender, EventArgs e)
        {
            try
            {
                GridViewRow gr = (GridViewRow)((DataControlFieldCell)((LinkButton)sender).Parent).Parent;
                Label lblItemCode = (Label)gr.FindControl("lblItemCode");
                Label lblInStockVSM = (Label)gr.FindControl("lblInStockVSM");
                if (lblItemCode != null && lblInStockVSM != null)
                {
                    string popup = "OpenAvailablePopup('" + lblItemCode.Text + "','" + lblInStockVSM.Text + "','Dealer')";
                    ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "CallJS", popup, true);
                }
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
        }

        protected void btnNew_Click(object sender, EventArgs e)
        {
            ClearScreen();
        }

    }
}